package tsm.main;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.PlayerListener;
import javax.microedition.media.control.VolumeControl;
import javax.microedition.rms.RecordStore;
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.TextMessage;

import tsm.constant.ClientConstant;
import tsm.constant.Language;
import tsm.constant.MagicConstant;
import tsm.constant.PageConstant;
import tsm.file.FileConnector;
import tsm.model.Buddy;
import tsm.model.InviteConference;
import tsm.network.BeUSession;
import tsm.network.NetworkCore;
import tsm.painter.StatusNoticePainter;
import tsm.painter.WaitingNoticePainter;
import tsm.widget.BlackListPage;
import tsm.widget.BuddyInviteConferencePage;
import tsm.widget.BuddyPage;
import tsm.widget.ChatListPage;
import tsm.widget.ChatPage;
import tsm.widget.ConferenceListPage;
import tsm.widget.ConferencePage;
import tsm.widget.ConfirmJoinConferencePage;
import tsm.widget.EmotionsImplementation;
import tsm.widget.FileBrowser;
import tsm.widget.IAction;
import tsm.widget.MenulessTextField;
import tsm.widget.Page;
import tsm.widget.PhotoViewerPage;
import tsm.widget.PlayerPage;
import tsm.widget.ProgressPage;
import tsm.widget.SplashPage;
import tsm.widget.YahooBuddyPage;

import com.core.tsm.Button;
import com.core.tsm.Command;
import com.core.tsm.Component;
import com.core.tsm.Container;
import com.core.tsm.Dialog;
import com.core.tsm.Display;
import com.core.tsm.Form;
import com.core.tsm.Image;
import com.core.tsm.Label;
import com.core.tsm.TextArea;
import com.core.tsm.TextField;
import com.core.tsm.VirtualKeyboard;
import com.core.tsm.animations.CommonTransitions;
import com.core.tsm.events.ActionEvent;
import com.core.tsm.events.ActionListener;
import com.core.tsm.layouts.BorderLayout;
import com.core.tsm.layouts.FlowLayout;
import com.core.tsm.list.DefaultListModel;
import com.core.tsm.painter.PainterChain;
import com.core.tsm.plaf.Border;
import com.core.tsm.plaf.UIManager;
import com.core.tsm.util.Resources;

public class Core implements ActionListener, PlayerListener {

	private static Core instance;
	private Resources res;
	// private static String localLanguage;
	private static Vector pages;
	private static Page currentPage;
	private static int pagesSize;
	private static Player player;
	private StatusNoticePainter statusNotice;
	private WaitingNoticePainter waitingNoticePainter;
	private boolean isVibrate;
	// private Container smileyBody;
	private Dialog smileyDialog;
	private Dialog infoDialog;
	private TextArea info;
	public String username;
	public String yahooUsername;
	public boolean isBegin;
	public boolean isLoginSuccess;
	public DefaultListModel friendListModel; // friendlist
	public DefaultListModel yahooFriendListModel; // yahoo friendlist
	public DefaultListModel chatListName; // current chatters
	public DefaultListModel blackList; // current ignore chat
	public Vector inviteConferenceList; // invite list when start conference
	public long currentConferenceId; // current conference for send with
										// inviteMember
	public boolean isStartConference; // start conference or not
	public Vector conferenceListPages;
	public DefaultListModel conferenceListName;
	public byte[] SE = { (byte) 0 };
	private PlayerPage playerPage;
	private BuddyPage buddyPage;
	private YahooBuddyPage yahooBuddyPage;
	private ProgressPage progressPage;
	private ChatListPage chatListPage;
	private ConferenceListPage conferenceListPage;
	private BuddyInviteConferencePage buddyInviteConferencePage;
	private ConfirmJoinConferencePage confirmJoinConferencePage;
	private BlackListPage blackListPage;
	private PhotoViewerPage photoViewerPage;
	private Vector userInfo;
	private Vector chatPagesList;
	public Vector waitingConfirmConference;
	public Resources theme;
	private boolean isMute;
	private boolean bMuzikDisable;
	public Image swImage;
	public SplashPage splashPage;
	public Hashtable checkSumPage;

	public static Core getInstance() {
		return instance;
	}

	protected void startApp() {
		instance = this;
		// try {
		// localLanguage = System.getProperty("microedition.locale");
		// // System.out.println("localLanguage " + localLanguage);
		// } catch (Throwable t) {
		// // can throw a security exception in an applet
		// }
		try {
			// set the theme
			// Resources theme = Resources.open("/LWUITtheme.res");
			// Resources theme = Resources.open("/AndroidTheme.res");
			// Resources theme = Resources.open("/android.res");
			// Resources theme = Resources.open("/wunderkammertheme.res");
			// Resources theme = Resources.open("/iPhoneTheme.res");
			// Resources theme = Resources.open("/wood.res");
			// Resources theme = Resources.open("/mytheme.res");
			theme = Resources.open("/beU.res");
			// getResource();
			UIManager.getInstance().setThemeProps(theme.getTheme(theme.getThemeResourceNames()[0]));
			UIManager.getInstance().setResourceBundle(theme.getL10N("vi", "en"));
			UIManager.getInstance().getLookAndFeel().setDefaultMenuTransitionIn(CommonTransitions.createEmpty());
			UIManager.getInstance().getLookAndFeel().setDefaultMenuTransitionOut(CommonTransitions.createEmpty());
			VirtualKeyboard.setTransitionIn(CommonTransitions.createEmpty());
			VirtualKeyboard.setTransitionOut(CommonTransitions.createEmpty());
			VirtualKeyboard.setVKBTint(new TextField(), 255);
			isVibrate = true;
			isBegin = true;
			isLoginSuccess = false;
			checkSumPage = new Hashtable();
			friendListModel = new DefaultListModel();
			yahooFriendListModel = new DefaultListModel();
			chatListName = new DefaultListModel();
			userInfo = new Vector();
			inviteConferenceList = new Vector();
			conferenceListPages = new Vector();
			conferenceListName = new DefaultListModel();
			// blackList = new Vector(); //NOT NEED
			pages = new Vector();
			chatPagesList = new Vector();
			waitingConfirmConference = new Vector();
			// open the resources file that contains all the icons

			// although calling directly to setMainForm(res) will work on
			// most devices, a good coding practice will be to allow the midp
			// thread to return and to do all the UI on the EDT.
			Display.getInstance().callSerially(new Runnable() {
				public void run() {
					setMainForm(res);
				}
			});
			splashPage = new SplashPage(-1, -1);
			splashPage.run(this, true);
			splashPage.show();
			loadCachePage();
			// try {
			// Thread.sleep(2000);
			// } catch (InterruptedException e) {
			// e.printStackTrace();
			// }
			doConnect();
		} catch (Throwable ex) {
			ex.printStackTrace();
			Dialog.show(Language.ERROR[ClientConstant.LANGUAGE], ex.getMessage(), Language.CLOSE[ClientConstant.LANGUAGE], null);
		}
	}

	private void loadCachePage() {
		try {
			ByteArrayInputStream b = null;
			try {
				byte[] data = loadMagicPageSumFromRMS(PageConstant.LOGIN_PAGE_ID);
				int checkSum = loadInt("mpchecksum_" + PageConstant.LOGIN_PAGE_ID);
				if (data != null) {
					b = new ByteArrayInputStream(data);
					MagicExecutor.deCompilePage(b, false);
					b.close();
					if (checkSum != -1) {
						Integer paL = new Integer(PageConstant.LOGIN_PAGE_ID);
						if (checkSumPage.containsKey(paL)) {
							checkSumPage.put(paL, new Integer(checkSum));
						}
					}
				}
				data = null;
				data = loadMagicPageSumFromRMS(PageConstant.MAIN_PAGE_ID);
				checkSum = loadInt("mpchecksum_" + PageConstant.MAIN_PAGE_ID);
				if (data != null) {
					b = new ByteArrayInputStream(data);
					MagicExecutor.deCompilePage(b, false);
					b.close();
					if (checkSum != -1) {
						Integer paL = new Integer(PageConstant.MAIN_PAGE_ID);
						if (checkSumPage.containsKey(paL)) {
							checkSumPage.put(paL, new Integer(checkSum));
						}
					}
				}
			} catch (Exception e) {
			} finally {
				if (b != null) {
					b.close();
				}
			}
		} catch (Exception e) {
		}
	}

	public void doConnect() {
		if (!NetworkCore.isConnected()) {
			String[] IPs = loadIPs();
			int[] ports = loadPorts();
			if (IPs.length == 0) {
				IPs = ClientConstant.DEFAULT_IP;
				ports = ClientConstant.DEFAULT_PORT;
			}
			int n = (int) (System.currentTimeMillis() % IPs.length);
			// System.out.println("Doconnect ips length " + IPs.length +
			// " choose " + n);
			NetworkCore.connect(IPs[n], ports[n]);
		}
	}

	protected void pauseApp() {

	}

	protected void destroyApp(boolean unconditional) {

	}

	public void actionPerformed(ActionEvent evt) {
		// System.out.println("=================actionPerformed getKeyEvent = "
		// + evt.getKeyEvent());
		Command cmd = evt.getCommand();
		switch (cmd.getId()) {
		case ClientConstant.BACK_CMD: {
			// System.out.println("BACK_CMD performed");
			removePage(-1, true);
			break;
		}
		case ClientConstant.MAGIC_CMD: {
			byte[] action = (byte[]) cmd.getClientProperty(MagicConstant.COMPONENT_ACTION_KEY);
			MagicExecutor.deCompilePage(new ByteArrayInputStream(action), true);
			break;
		}
		case ClientConstant.EXIT_CMD: {
			closeApp();
			Display.getInstance().exitApplication();
			break;
		}
		case ClientConstant.CLEAR_CMD: {
			// System.out.println("CLEAR_CMD performed");
			MenulessTextField tf = (MenulessTextField) evt.getCommand().getClientProperty("MenulessTextField");
			tf.deleteChar();
			break;
		}
		case ClientConstant.CLOSE_PAGE_CMD: {
			// System.out.println("CLOSE_PAGE_CMD performed");
			removeCurrentPage(true);
			break;
		}
		case ClientConstant.SMILEY_CMD: {
			// System.out.println("SMILEY_CMD performed");
			showSmileyDialog();
			break;
		}
		case ClientConstant.SEND_FILE_CMD: {
			// System.out.println("SEND_FILE_CMD performed");
			break;
		}
		case ClientConstant.BUZZ_CMD: {
			// System.out.println("BUZZ_CMD performed");
			String buzzTo = (String) evt.getCommand().getClientProperty("Buzz");
			Page cur = getCurrentPage();
			if (cur instanceof ChatPage) {
				ChatPage p = (ChatPage) currentPage;
				p.addItems(username, "Hù!");
				startVibrate();
				playSound();
			}
			BeUSession.sendBuzz(buzzTo);
			break;
		}
		case ClientConstant.BUZZ_YAHOO_CMD: {
			String buzzTo = (String) evt.getCommand().getClientProperty("Buzz");
			Page cur = getCurrentPage();
			if (cur instanceof ChatPage) {
				ChatPage p = (ChatPage) currentPage;
				p.addItems(username, "Hù!");
				startVibrate();
				playSound();
			}
			BeUSession.buzzYahoo(buzzTo);
			break;
		}
		case ClientConstant.ADD_FRIEND_CMD:
			// System.out.println("ADD_FRIEND_CMD performed");
			BeUSession.requestAddFriend(BuddyPage.getInstance().getSelectedName(), BuddyPage.getInstance().getGroups());
			break;
		case ClientConstant.GET_ME_CMD:
			// System.out.println("GET_ME_CMD performed");
			BeUSession.getMEPage(BuddyPage.getInstance().getSelectedId());
			break;
		case ClientConstant.REMOVE_FRIEND_CMD:
			String badGuy = BuddyPage.getInstance().getSelectedName();
			BeUSession.removeFriend(badGuy);
			removeBuddy(badGuy);
			break;
		case ClientConstant.CHANGE_GROUP_CMD:
			BeUSession.requestChangeGroup(BuddyPage.getInstance().getSelectedName(), BuddyPage.getInstance().getGroups());
			break;
//		case ClientConstant.CHANGE_STATUS_CMD:
//			BeUSession.requestChangeStatus();
//			break;
		case ClientConstant.CHANGE_STATUS_YAHOO_CMD: {
			BeUSession.setStatusYahooBean();
			break;
		}
		case ClientConstant.ADD_BLACKLIST_CMD: {
			String victim = BuddyPage.getInstance().getSelectedName();
			doActionAddBlacklist(victim);
			break;
		}
		case ClientConstant.ADD_BLACKLIST_CHAT_CMD: {
			String victim = (String) evt.getCommand().getClientProperty("BadGuy");
			doActionAddBlacklist(victim);
			break;
		}
//		case ClientConstant.BLACK_LIST_CMD:
//			createBlackListPage();
//			break;
		case ClientConstant.BACK_TO_PAGE_CMD:
			removePage(-1, true);
			break;
		case ClientConstant.CLOSE_BUDDY_INVITE_CONFERENCE_PAGE_CMD: {
			BuddyInviteConferencePage buddyInviteConferencePage = (BuddyInviteConferencePage) evt.getCommand().getClientProperty("inviConfP");
			buddyInviteConferencePage.resetStatusInvite(inviteConferenceList);
			inviteConferenceList.removeAllElements();
			isStartConference = false;
			removePage(-1, true);
			break;
		}
		case ClientConstant.INVITE_CONFERENCE_CMD: {
			if (inviteConferenceList.size() > 0) {
				BuddyInviteConferencePage buddyInviteConferencePage = (BuddyInviteConferencePage) evt.getCommand().getClientProperty("inviConfP");
				BeUSession.inviteMembers(currentConferenceId, isStartConference, inviteConferenceList);
				buddyInviteConferencePage.resetStatusInvite(inviteConferenceList);
				removeCurrentPage(true); // remove invite buddy page
				// System.out.println("INVITE_CONFERENCE_CMD currentConferenceId = "
				// + currentConferenceId);
				// if (isStartConference) {
				// // createConferencePage(currentConferenceId, null, true, new
				// Vector());
				// }
				isStartConference = false;
				// currentConferenceId = -1;
			} else {
				showInfoDialog(Language.INFO[ClientConstant.LANGUAGE], Language.INVITE_AT_LEAST_CONFERENCE[ClientConstant.LANGUAGE]);
			}
			break;
		}
		case ClientConstant.CREATE_CONFERENCE_CMD:
			BeUSession.createConference();
			break;
		case ClientConstant.LEAVE_CONFERENCE_CMD: {
			long conferenceId = ((Long) evt.getCommand().getClientProperty("ConferenceId")).longValue();
			BeUSession.leaveConference(conferenceId);
			removeConference(conferenceId);
			removeCurrentPage(true);
			break;
		}
		case ClientConstant.KICK_USER_CONFERENCE_CMD: {
			long conferenceId = ((Long) evt.getCommand().getClientProperty("ConferenceId")).longValue();
			BeUSession.callKickConferencePage(conferenceId);
			break;
		}
		case ClientConstant.INIVTE_MEMBER_CONFERENCE_CMD: {
			Core.getInstance().currentConferenceId = ((Long) evt.getCommand().getClientProperty("ConferenceId")).longValue();
			Core.getInstance().isStartConference = false;
			Core.getInstance().createBuddyInviteConferencePage();
			break;
		}
		case ClientConstant.REMOVE_BLACKLIST_CMD: {
			String victim = BlackListPage.getInstance().getSelectedName();
			if (victim != null && victim.length() > 0) {
				// System.out.println("REMOVE_BLACKLIST_CMD: " + victim);
				BeUSession.removeBlackList(victim);
				int n = blackList.getSize();
				if (n > 0) {
					for (int i = n; --i >= 0;) {
						if (blackList.getItemAt(i).equals(victim)) {
							blackList.removeItem(i);
							return;
						}
					}
				}
			}
			break;
		}
		case ClientConstant.CLOSE_CHAT_PAGE_CMD: {
			// System.out.println("CLOSE_CHAT_PAGE_CMD performed");
			removeCurrentPage(true);
			String chatName = (String) evt.getCommand().getClientProperty("ChatName");
			removeChatPageByUsername(chatName);
			removeChatListName(chatName);
			break;
		}
		case ClientConstant.SEND_PHOTO_CMD: {
			removeCurrentPage(false);
			BeUSession.requestUploadImage(PhotoViewerPage.data);
			break;
		}
		case ClientConstant.CANCEL_UPLOAD_CMD: {
			BeUSession.sessionId = -1;
			BeUSession.cancelUploadImage();
			removeCurrentPage(true);
			break;
		}
		case ClientConstant.TRY_AGAIN_CMD: {
			doConnect();
			break;
		}
		case ClientConstant.SEND_CHAT_CHATPAGE_CMD: {
			ChatPage chatPage = (ChatPage) evt.getCommand().getClientProperty("chatP");
			chatPage.doSendChat();
			break;
		}
		case ClientConstant.SEND_CHAT_CONFPAGE_CMD: {
			ConferencePage conferencePage = (ConferencePage) evt.getCommand().getClientProperty("confP");
			conferencePage.doSendChat();
			break;
		}
		case ClientConstant.ADD_MORE_BAD_GUY_CMD: {
			String name = BlackListPage.getInstance().t.getText();
			doActionAddBlacklist(name);
			break;
		}
		case ClientConstant.LOGOUT_YAHOO_CMD: {
			doSignOutYahoo();
			break;
		}
		case ClientConstant.CHAT_LIST_CMD: {
			createChatListPage();
			break;
		}
		case ClientConstant.SHOW_ONLINE_CMD: {
			BuddyPage.getInstance().filteredIndex.filter();
			break;
		}
		case ClientConstant.SHOW_ONLINE_YAHOO_CMD: {
			YahooBuddyPage.getInstance().filteredIndex.filter();
			break;
		}
		default:
			break;
		}
	}

	public void doSignOutYahoo() {
		removePage(PageConstant.YAHOO_BUDDY_PAGE_ID, true);
		try {
			if (yahooFriendListModel != null) {
				yahooFriendListModel.removeAll();
				yahooFriendListModel = null;
			}
		} catch (Exception e) {
		}
		yahooBuddyPage = null;
		BeUSession.logoutYahoo();
	}

	// start up
	private void setMainForm(Resources r) {
		// Font.setBitmapFontEnabled(true);
		// if (r.getL10NResourceNames().length > 0 && localLanguage != null) {
		// UIManager.getInstance().setResourceBundle(
		// r.getL10N("localize", localLanguage));
		//
		// // don't use bitmap fonts for localization since we still want to
		// // run on low end devices!
		// if (!"en".equals(localLanguage)) {
		// Font.setBitmapFontEnabled(false);
		// }
		// }

		// Form form = new Form();
		// form.setTitle("Test");
		// form.addComponent(new Label("Hi"));
		// form.addComponent(new TextField("Chao ban"));
		// form.addComponent(new Button("hello"));
		// form.show();
		loadSmiley();
		// ChatPage chatPage = new ChatPage(PageConstant.CHAT_PAGE_ID);
		// addPage(chatPage);
		// chatPage.run(this);

		// BuddyPage buddyPage = new BuddyPage(PageConstant.BUDDY_PAGE_ID, 111);
		// addPage(buddyPage);
		// buddyPage.run(this);

		// TalkPage talkPage = new TalkPage(123);
		// talkPage.run(this);
		// BuddyPage buddyPage = new BuddyPage(1111111111);
		// buddyPage.run(this);

		// AvatarPage avatarPage = new AvatarPage(1111111111, 22222);
		// avatarPage.run(this, true);
		// avatarPage.show();

		try {
			swImage = Image.createImage("/avatar.png");
		} catch (IOException ex) {
			ex.printStackTrace();
		}

		// PlayerPage playerPage = new PlayerPage(222, 333);
		// playerPage.run(this);
		// playerPage.show();

		// showProcessingDialog();

		// MagicExecutor.deCompilePage(new ByteArrayInputStream(MagicGenerator
		// .trySample()));
		// SplashPage splashPage = new SplashPage(-1111, -1111);
		// splashPage.run(this);
		// splashPage.show();

		// showWaitingDialog();
	}

	// ======================================Loading resource
	// private void getResource() {
	// byte[] data = loadRMS("test");
	// if (data != null && data.length > 0) {
	// ByteArrayInputStream byteArrayInputStream = new
	// ByteArrayInputStream(data);
	// try {
	// theme = Resources.open(byteArrayInputStream);
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// System.out.println("Get from cache done");
	// return;
	// }
	// HttpConnection connection = null;
	// InputStream inputstream = null;
	// try {
	// System.out.println("Begin Get from NET");
	// connection = (HttpConnection)
	// Connector.open("http://127.0.0.1/mytheme.res");
	// // HTTP Request
	// connection.setRequestMethod(HttpConnection.GET);
	// connection.setRequestProperty("Content-Type", "//text plain");
	// connection.setRequestProperty("Connection", "close");
	// // HTTP Response
	// System.out.println("Status Line Code: " + connection.getResponseCode());
	// System.out.println("Status Line Message: " +
	// connection.getResponseMessage());
	// if (connection.getResponseCode() == HttpConnection.HTTP_OK) {
	// System.out.println(connection.getHeaderField(0) + " " +
	// connection.getHeaderFieldKey(0));
	// System.out.println("Header Field Date: " +
	// connection.getHeaderField("date"));
	// inputstream = connection.openInputStream();
	// // theme = Resources.open(inputstream);
	//
	// int length = (int) connection.getLength();
	// System.out.println("length " + length);
	// if (length != -1) {
	// byte incomingData[] = new byte[length];
	// int dataRead = inputstream.read(incomingData);
	// ByteArrayInputStream byteArrayInputStream = new
	// ByteArrayInputStream(incomingData);
	// theme = Resources.open(byteArrayInputStream);
	// saveRMS("test", incomingData);
	// System.out.println("str1 " + dataRead);
	// } else {
	// ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
	// int ch;
	// while ((ch = inputstream.read()) != -1) {
	// bytestream.write(ch);
	// }
	// String str = new String(bytestream.toByteArray());
	// System.out.println("str2 " + str);
	// bytestream.close();
	// }
	// }
	// } catch (IOException error) {
	// System.out.println("Caught IOException: " + error.toString());
	// } finally {
	// if (inputstream != null) {
	// try {
	// inputstream.close();
	// } catch (Exception error) {
	// /* log error */
	// }
	// }
	// if (connection != null) {
	// try {
	// connection.close();
	// } catch (Exception error) {
	// /* log error */
	// }
	// }
	// }
	// }

	private void loadSmiley() {
		try {
			smileyDialog = new Dialog();
			smileyDialog.setLayout(new FlowLayout(Component.CENTER));
			Image smileyImage = Image.createImage("/emotion.png");
			// smileyBody = new Container();
			// smileyBody.setScrollable(false);
			// smileyBody.setLayout(new FlowLayout(Component.CENTER));
			// smileyBody.setShouldCalcPreferredSize(true);
			Border border = Border.createRoundBorder(4, 4, 0xffffff);
			Border border1 = Border.createLineBorder(1, 0x33b7f8);
			for (int i = 0; i < 30; i++) {
				Image aSmile = smileyImage.subImage(i * EmotionsImplementation.eWidth, 0, EmotionsImplementation.eWidth, EmotionsImplementation.eWidth, true);
				Button button = new Button(aSmile);
				button.setAlignment(Button.CENTER);
				button.getUnselectedStyle().setBgImage(null);
				button.getSelectedStyle().setBgImage(null);
				button.getPressedStyle().setBgImage(null);
				button.getUnselectedStyle().setBgTransparency(255);
				button.getSelectedStyle().setBgTransparency(255);
				// button.getUnselectedStyle().setBgColor(0x0b49e7);
				// button.getSelectedStyle().setBgColor(0x0b49e7);
				button.getSelectedStyle().setBorder(border1);

				button.getSelectedStyle().setPadding(Button.TOP, 2);
				button.getSelectedStyle().setMargin(Button.TOP, 2);
				button.getSelectedStyle().setPadding(Button.BOTTOM, 1);
				button.getSelectedStyle().setMargin(Button.BOTTOM, 1);
				button.getSelectedStyle().setPadding(Button.LEFT, 1);
				button.getSelectedStyle().setMargin(Button.LEFT, 1);
				button.getSelectedStyle().setPadding(Button.RIGHT, 1);
				button.getSelectedStyle().setMargin(Button.RIGHT, 1);
				button.getUnselectedStyle().setPadding(Button.TOP, 2);
				button.getUnselectedStyle().setMargin(Button.TOP, 2);
				button.getUnselectedStyle().setPadding(Button.BOTTOM, 1);
				button.getUnselectedStyle().setMargin(Button.BOTTOM, 1);
				button.getUnselectedStyle().setPadding(Button.LEFT, 1);
				button.getUnselectedStyle().setMargin(Button.LEFT, 1);
				button.getUnselectedStyle().setPadding(Button.RIGHT, 1);
				button.getUnselectedStyle().setMargin(Button.RIGHT, 1);
				button.getPressedStyle().setPadding(Button.TOP, 2);
				button.getPressedStyle().setMargin(Button.TOP, 2);
				button.getPressedStyle().setPadding(Button.BOTTOM, 1);
				button.getPressedStyle().setMargin(Button.BOTTOM, 1);
				button.getPressedStyle().setPadding(Button.LEFT, 1);
				button.getPressedStyle().setMargin(Button.LEFT, 1);
				button.getPressedStyle().setPadding(Button.RIGHT, 1);
				button.getPressedStyle().setMargin(Button.RIGHT, 1);

				button.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						int index = smileyDialog.getComponentIndex((Component) evt.getSource());
						if (smileyDialog == null) {
							smileyDialog = (Dialog) Display.getInstance().getCurrent();
							smileyDialog.dispose();
						} else {
							smileyDialog.dispose();
						}
						if (currentPage instanceof ChatPage) {
							((ChatPage) currentPage).insertSmiley(index);
							currentPage.show();
						} else if (currentPage instanceof ConferencePage) {
							((ConferencePage) currentPage).insertSmiley(index);
							currentPage.show();
						}
					}
				});
				// button.setUnselectedStyle(style);
				// smileyBody.addComponent(button);
				smileyDialog.addComponent(button);
			}

			smileyDialog.getTitleStyle().setBgImage(null);
			// smileyDialog.getStyle().setBorder(border);

			smileyDialog.getTitleStyle().setPadding(Button.TOP, 0);
			smileyDialog.getTitleStyle().setMargin(Button.TOP, 0);
			smileyDialog.getTitleStyle().setPadding(Button.BOTTOM, 0);
			smileyDialog.getTitleStyle().setMargin(Button.BOTTOM, 0);
			// smileyDialog.getContentPane().setFocus(true);
			smileyDialog.getContentPane().getSelectedStyle().setPadding(Button.TOP, 0);
			smileyDialog.getContentPane().getSelectedStyle().setMargin(Button.TOP, 0);
			smileyDialog.getContentPane().getUnselectedStyle().setPadding(Button.TOP, 0);
			smileyDialog.getContentPane().getUnselectedStyle().setMargin(Button.TOP, 0);
			smileyDialog.getContentPane().getSelectedStyle().setPadding(Button.BOTTOM, 0);
			smileyDialog.getContentPane().getSelectedStyle().setMargin(Button.BOTTOM, 0);
			smileyDialog.getContentPane().getUnselectedStyle().setPadding(Button.BOTTOM, 0);
			smileyDialog.getContentPane().getUnselectedStyle().setMargin(Button.BOTTOM, 0);
			smileyDialog.getContentPane().getSelectedStyle().setPadding(Button.LEFT, 0);
			smileyDialog.getContentPane().getSelectedStyle().setMargin(Button.LEFT, 0);
			smileyDialog.getContentPane().getUnselectedStyle().setPadding(Button.LEFT, 0);
			smileyDialog.getContentPane().getUnselectedStyle().setMargin(Button.LEFT, 0);
			smileyDialog.getContentPane().getSelectedStyle().setPadding(Button.RIGHT, 0);
			smileyDialog.getContentPane().getSelectedStyle().setMargin(Button.RIGHT, 0);
			smileyDialog.getContentPane().getUnselectedStyle().setPadding(Button.RIGHT, 0);
			smileyDialog.getContentPane().getUnselectedStyle().setMargin(Button.RIGHT, 0);
			smileyDialog.getContentPane().getSelectedStyle().setBorder(null);
			smileyDialog.getContentPane().getUnselectedStyle().setBorder(null);
			smileyDialog.getContentPane().getUnselectedStyle().setBgImage(null);
			Dialog.setDialogTitleCompatibilityMode(true);
			smileyDialog.getContentPane().getUnselectedStyle().setBorder(border);
			smileyDialog.getContentPane().getUnselectedStyle().setBorder(border);
			Dialog.setDialogTitleCompatibilityMode(false);

			// smileyDialog.addComponent(smileyBody);

			// smileyDialog.getUnselectedStyle().setBorder(border);
			// Dialog.setAutoAdjustDialogSize(true);
			// Dialog.setDisableStaticDialogScrolling(true);
			// smileyDialog.setShouldCalcPreferredSize(true);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// ======================RMS
	public void saveRMS(String filename, byte[] data) {
		try {
			RecordStore rec = RecordStore.openRecordStore("ms" + filename, true);
			if (rec.getNumRecords() > 0)
				rec.setRecord(1, data, 0, data.length);
			else {
				rec.addRecord(data, 0, data.length);
			}
			rec.closeRecordStore();
		} catch (Exception e) {
		}
	}

	public byte[] loadRMS(String filename) {
		RecordStore rec;
		byte[] data;
		try {
			rec = RecordStore.openRecordStore("ms" + filename, false);
			data = rec.getRecord(1);
			rec.closeRecordStore();
		} catch (Exception e) {
			return null;
		}
		return data;
	}

	public int toInt(byte b1, byte b2, byte b3, byte b4) {
		return (b1 << 24) & 0xFF000000 | (b2 << 16) & 0x00FF0000 | (b3 << 8) & 0x0000FF00 | b4 & 0x000000FF;
	}

	public byte[] toBytes(int i) {
		byte data[] = new byte[4];
		data[0] = (byte) (i >> 24);
		data[1] = (byte) ((i & 0x00FF0000) >> 16);
		data[2] = (byte) ((i & 0x0000FF00) >> 8);
		data[3] = (byte) ((i & 0x000000FF));
		return data;
	}

	public static byte[] longToBytes(long foo) {
		byte[] writeBuffer = new byte[8];
		writeBuffer[0] = (byte) (foo >>> 56);
		writeBuffer[1] = (byte) (foo >>> 48);
		writeBuffer[2] = (byte) (foo >>> 40);
		writeBuffer[3] = (byte) (foo >>> 32);
		writeBuffer[4] = (byte) (foo >>> 24);
		writeBuffer[5] = (byte) (foo >>> 16);
		writeBuffer[6] = (byte) (foo >>> 8);
		writeBuffer[7] = (byte) (foo >>> 0);
		return writeBuffer;
	}

	public static long bytes2Long(byte[] data) {
		long res = 0;
		for (int i = 0; i < 8; i++) {
			res <<= 8;
			res |= (0xFF & data[i]);
		}
		return res;
	}

	public int loadInt(String key) {
		byte[] tem = loadRMS(key);
		if (tem == null || tem.length != 4) {
			return -1;
		} else {
			int cs = toInt(tem[0], tem[1], tem[2], tem[3]);
			return cs;
		}
	}

	//
	public void writeString(ByteArrayOutputStream s, String str) throws Exception {
		s.write(str.getBytes());
		s.write(SE);
	}

	public void writeInt(ByteArrayOutputStream s, int i) throws Exception {
		s.write(toBytes(i));
	}

	public void writeLong(ByteArrayOutputStream s, long i) throws Exception {
		s.write(longToBytes(i));
	}

	public int readInt(ByteArrayInputStream s) {
		return toInt((byte) s.read(), (byte) s.read(), (byte) s.read(), (byte) s.read());
	}

	public long readLong(ByteArrayInputStream s) throws IOException {
		byte[] data = new byte[8];
		s.read(data);
		return bytes2Long(data);
	}

	public static String readString(ByteArrayInputStream s) {
		String str = "";
		while (true) {
			int k = s.read();
			if (k == 0)
				break;
			str += (char) ((byte) k);
		}
		return str;
	}

	private void saveBuddyToRMS(DefaultListModel buddies, String nickName) {
		try {
			ByteArrayOutputStream s = new ByteArrayOutputStream();
			int n = buddies.getSize();
			writeInt(s, n);
			for (int i = 0; i < n; i++) {
				Buddy buddy = (Buddy) buddies.getItemAt(i);
				writeLong(s, buddy.getUserId());
				writeString(s, buddy.getUsername());
			}
			saveRMS("tsmbuddies_" + nickName, s.toByteArray());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void loadBuddyFromRMS(String nickName) {
		try {
			byte[] data = loadRMS("tsmbuddies_" + nickName);
			if (data != null) {
				ByteArrayInputStream s = new ByteArrayInputStream(data);
				int n = readInt(s);
				DefaultListModel buddies = new DefaultListModel();
				for (int i = 0; i < n; i++) {
					Buddy buddy = new Buddy();
					long id = readLong(s);
					String fName = readString(s);
					buddy.setUserId(id);
					buddy.setAvatarId(-1);
					buddy.setUsername(fName);

					Label description = new Label(swImage);
					description.setTextPosition(Label.LEFT);
					description.getSelectedStyle().setBgTransparency(255);
					description.getSelectedStyle().setBgColor(0x138ef6);
					description.getSelectedStyle().setPadding(Button.TOP, 0);
					description.getSelectedStyle().setMargin(Button.TOP, 0);
					description.getSelectedStyle().setPadding(Button.BOTTOM, 1);
					description.getSelectedStyle().setMargin(Button.BOTTOM, 1);
					description.getSelectedStyle().setPadding(Button.LEFT, 0);
					description.getSelectedStyle().setMargin(Button.LEFT, 0);
					description.getSelectedStyle().setPadding(Button.RIGHT, 0);
					description.getSelectedStyle().setMargin(Button.RIGHT, 0);
					description.setFocus(true);
					Label titleLabel = new Label("");
					titleLabel.getSelectedStyle().setBgTransparency(255);
					titleLabel.getSelectedStyle().setBgColor(0x138ef6);
					titleLabel.getSelectedStyle().setPadding(Button.TOP, 0);
					titleLabel.getSelectedStyle().setMargin(Button.TOP, 0);
					titleLabel.getSelectedStyle().setPadding(Button.BOTTOM, 1);
					titleLabel.getSelectedStyle().setMargin(Button.BOTTOM, 1);
					titleLabel.getSelectedStyle().setPadding(Button.LEFT, 0);
					titleLabel.getSelectedStyle().setMargin(Button.LEFT, 0);
					titleLabel.getSelectedStyle().setPadding(Button.RIGHT, 0);
					titleLabel.getSelectedStyle().setMargin(Button.RIGHT, 0);
					Container selected = new Container(new BorderLayout());
					selected.getSelectedStyle().setPadding(Button.TOP, 0);
					selected.getSelectedStyle().setMargin(Button.TOP, 0);
					selected.getSelectedStyle().setPadding(Button.BOTTOM, 0);
					selected.getSelectedStyle().setMargin(Button.BOTTOM, 0);
					selected.getSelectedStyle().setPadding(Button.LEFT, 0);
					selected.getSelectedStyle().setMargin(Button.LEFT, 0);
					selected.getSelectedStyle().setPadding(Button.RIGHT, 0);
					selected.getSelectedStyle().setMargin(Button.RIGHT, 0);
					selected.addComponent(BorderLayout.CENTER, titleLabel);
					selected.addComponent(BorderLayout.EAST, description);
					titleLabel.setFocus(true);
					description.setFocus(true);
					buddy.setAvatarLabel(description);
					buddy.setStatusLabel(titleLabel);
					buddy.setAvatarContainer(selected);

					buddies.addItem(buddy);
				}
				friendListModel = buddies;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void saveCheckSumToRMS(int checkSum, String nickName) {
		try {
			saveRMS("tsmchecksum_" + nickName, toBytes(checkSum));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public int loadCheckSumFromRMS(String nickName) {
		return loadInt("tsmchecksum_" + nickName);
	}

	public int loadMagicCheckSumFromRMS(int pageId) {
		Integer paL = new Integer(pageId);
		if (checkSumPage.containsKey(paL)) {
			//			System.out.println("loadMagicCheckSumFromRMS hrra get " + pageId + " from RAM");
			return ((Integer) checkSumPage.get(paL)).intValue();
		}
		int checkSum = loadInt("mpchecksum_" + pageId);
		if (checkSum != -1) {
			checkSumPage.put(new Integer(pageId), new Integer(checkSum));
		}
		return checkSum;
	}

	public void saveMagicDataToRMS(int pageId, int checkSum, byte[] data) {
		try {
			saveRMS("mpchecksum_" + pageId, toBytes(checkSum));
			saveRMS("mpdata_" + pageId, data);
			Integer paL = new Integer(pageId);
			if (checkSumPage.containsKey(paL)) {
				checkSumPage.remove(paL);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public byte[] loadMagicPageSumFromRMS(int pageId) {
		return loadRMS("mpdata_" + pageId);
	}

	public byte[] loadAvatarFromRMS(int avatarId) {
		return loadRMS("tsmavatar_" + avatarId);
	}

	public void saveAvatarToRMS(int avatarId, byte[] data) {
		try {
			saveRMS("tsmavatar_" + avatarId, data);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private int[] loadPorts() {
		int nIP = loadnIP();
		if (nIP < 0)
			return new int[0];
		int Ports[] = new int[nIP];
		for (int i = 0; i < nIP; i++) {
			Ports[i] = Integer.parseInt(loadPort(i));
		}
		return Ports;
	}

	public String loadPort(int n) {
		byte[] data = loadRMS("tsm_Port" + n);
		if (data == null)
			return null;
		else
			return new String(data);
	}

	private String[] loadIPs() {
		int nIP = loadnIP();
		if (nIP < 0)
			return new String[0];
		String IPs[] = new String[nIP];
		for (int i = 0; i < nIP; i++) {
			IPs[i] = loadIP(i);
		}
		return IPs;
	}

	public String loadIP(int n) {
		byte[] data = loadRMS("tsm_IP" + n);
		if (data == null)
			return null;
		else
			return new String(data);
	}

	public int loadnIP() {
		byte[] data;
		if ((data = loadRMS("tsmnIP")) == null)
			return -1;
		return data[0];
	}

	public void saveIPs(String[] ips) {
		saveNIP(ips.length);
		for (int i = 0; i < ips.length; i++) {
			saveIP(ips[i], i);
		}
	}

	public void savePorts(int[] ports) {
		for (int i = 0; i < ports.length; i++) {
			savePort(ports[i] + "", i);
		}
	}

	public void saveNIP(int currentLevel) {
		byte[] data = new byte[1];
		data[0] = (byte) currentLevel;
		saveRMS("tsmnIP", data);
	}

	public void saveIP(String IP, int n) {
		saveRMS("tsm_IP" + n, IP.getBytes());
	}

	public void savePort(String IP, int n) {
		saveRMS("tsm_Port" + n, IP.getBytes());
	}

	// ==============================Page Manager
	public synchronized Page getPageById(int pageId) {
		try {
			for (int i = pagesSize; --i >= 0;) {
				Page p = (Page) pages.elementAt(i);
				if (p.getPageId() == pageId)
					return p;
			}
		} catch (Exception e) {
		}
		return null;
	}

	public synchronized Page selectPage(int pageId) {
		try {
			int previousPageId = -1;
			if (currentPage != null) {
				previousPageId = currentPage.getPageId();
				if (previousPageId == pageId) {
					previousPageId = currentPage.getPreviousPageId();
				}
			}
			for (int i = pagesSize; --i >= 0;) {
				Page p = (Page) pages.elementAt(i);
				if (p.getPageId() == pageId) {
					p.setPreviousPageId(previousPageId);
					currentPage = p;
					closeDialog(null);
					currentPage.show();
					return p;
				}
			}
		} catch (Exception e) {
		}
		return null;
	}

	public synchronized int addPage(Page page) {
		int previousPageId = -1;
		try {
			if (currentPage != null) {
				previousPageId = currentPage.getPageId();
				if (previousPageId == page.getPageId()) {
					previousPageId = currentPage.getPreviousPageId();
				}
			}
			Page oldPage = getPageById(page.getPageId());
			if (oldPage == null) {
				pages.addElement(page);
				pagesSize = pages.size();
				currentPage = page;
			} else {
				oldPage.cleanup();
				pages.removeElement(oldPage);
				pages.addElement(page);
				currentPage = page;
			}
		} catch (Exception e) {
		}
		return previousPageId;
	}

	public synchronized Page createBlackListPage() {
		// System.out.println("Create BlackList Page");
		try {
			for (int i = pagesSize; --i >= 0;) {
				Page p = (Page) pages.elementAt(i);
				if (p instanceof BlackListPage) {
					int pageId = currentPage.getPageId();
					p.setPreviousPageId(pageId);
					currentPage = p;
					currentPage.show();
					return currentPage;
				}
			}
			int pageId = currentPage.getPageId();
			// System.out.println("Currentpageid " + pageId);
			if (blackListPage == null) {
				blackListPage = new BlackListPage(PageConstant.BLACK_LIST_PAGE_ID, pageId);
			}
			blackListPage.setPreviousPageId(pageId);
			pages.addElement(blackListPage);
			pagesSize = pages.size();
			currentPage = blackListPage;
			currentPage.run(this, true);
			return currentPage;
		} catch (Exception e) {
		}
		return null;
	}

	public synchronized Page createProgressPage() {
		// System.out.println("Create progress Page");
		try {
			for (int i = pagesSize; --i >= 0;) {
				Page p = (Page) pages.elementAt(i);
				if (p instanceof ProgressPage) {
					int pageId = currentPage.getPageId();
					p.setPreviousPageId(pageId);
					currentPage = p;
					currentPage.show();
					return currentPage;
				}
			}
			int pageId = currentPage.getPageId();
			// System.out.println("Currentpageid " + pageId);
			if (progressPage == null) {
				progressPage = new ProgressPage(PageConstant.PROGRESS_PAGE_ID, pageId);
			}
			progressPage.setPreviousPageId(pageId);
			pages.addElement(progressPage);
			pagesSize = pages.size();
			currentPage = progressPage;
			currentPage.run(this, true);
			return currentPage;
		} catch (Exception e) {
		}
		return null;
	}

	public synchronized Page createPlayerPage() {
		// System.out.println("Create player Page");
		try {
			for (int i = pagesSize; --i >= 0;) {
				Page p = (Page) pages.elementAt(i);
				if (p instanceof PlayerPage) {
					int pageId = currentPage.getPageId();
					p.setPreviousPageId(pageId);
					currentPage = p;
					currentPage.show();
					return currentPage;
				}
			}
			int pageId = currentPage.getPageId();
			// System.out.println("createPlayerPage Currentpageid " + pageId);
			if (playerPage == null) {
				playerPage = new PlayerPage(PageConstant.PLAYER_PAGE_ID, pageId);
			}
			playerPage.setPreviousPageId(pageId);
			pages.addElement(playerPage);
			pagesSize = pages.size();
			currentPage = playerPage;
			currentPage.run(this, true);
			// System.out.println("createPlayerPage done ");
			return currentPage;
		} catch (Exception e) {
		}
		return null;
	}

	public synchronized Page createConferencePage(long conferenceId, String conferenceName, boolean isShow, boolean isStart, Vector ul) {
		// System.out.println("Create Conference Page");
		ConferencePage conferencePage = null;
		try {
			String title = conferenceName;
			if (isStart) {
				title = "[P]-" + conferenceId + "-" + conferenceName;
			}
			for (int i = pagesSize; --i >= 0;) {
				Page p = (Page) pages.elementAt(i);
				if (p instanceof ConferencePage) {
					if (((ConferencePage) p).getOrginalTitle().equals(title)) {
						if (isShow) {
							int pageId = currentPage.getPageId();
							if (pageId != PageConstant.CONFERENCE_PAGE_ID) { // only
																				// set
																				// if
																				// #
																				// chatpageid
								p.setPreviousPageId(pageId);
							}
							currentPage = p;
							currentPage.show();
						}
						return currentPage;
					}
				}
			}
			int pageId = currentPage.getPageId();
			conferencePage = findConferencePageByTitle(title);
			// System.out.println("Currentpageid " + pageId);
			if (conferencePage != null) {
				if (isShow) {
					conferencePage.setPreviousPageId(pageId);
					currentPage = conferencePage;
					pages.addElement(conferencePage);
					pagesSize = pages.size();
					conferencePage.show();
				}
			} else {
				// System.out.println("Not found conferencepage in conferencelistpage! NEW now!");
				conferencePage = new ConferencePage(PageConstant.CONFERENCE_PAGE_ID, pageId, conferenceId);
				conferencePage.setOrginalTitle(title);
				conferenceListPages.addElement(conferencePage);
				conferenceListName.addItem(title);
				if (isShow) {
					conferencePage.setPreviousPageId(pageId);
					pages.addElement(conferencePage);
					pagesSize = pages.size();
					currentPage = conferencePage;
					currentPage.run(this, true);
				}
			}
		} catch (Exception e) {
		}
		return conferencePage;
	}

	public synchronized ChatPage addChatPage(String orginalTitle, boolean isShow, boolean mustCreated) {
		// System.out.println("Create Chat Page by name " + orginalTitle);
		ChatPage chatPage = null;
		try {
			for (int i = pagesSize; --i >= 0;) {
				Page p = (Page) pages.elementAt(i);
				if (p instanceof ChatPage) {
					chatPage = (ChatPage) p;
					if (chatPage.getOrginalTitle().equals(orginalTitle)) {
						if (isShow) {
							int pageId = currentPage.getPageId();
							if (pageId != PageConstant.CHAT_PAGE_ID) { // only
																		// set
																		// if #
																		// chatpageid
								chatPage.setPreviousPageId(pageId);
							}
							currentPage = chatPage;
							chatPage.show();
						}
						return chatPage;
					}
				}
			}
			// System.out.println("Not found chatpage in pages");
			chatPage = findChatPageByUsername(orginalTitle);
			int pageId = currentPage.getPageId();
			// System.out.println("Currentpageid " + pageId);
			if (chatPage != null) {
				if (isShow) {
					chatPage.setPreviousPageId(pageId);
					currentPage = chatPage;
					pages.addElement(chatPage);
					pagesSize = pages.size();
					chatPage.show();
				}
			} else {
				// System.out.println("Not found chatpage in chatpagelist! NEW now!");
				if (!mustCreated) { // case: onchangestatus not need created
					return null;
				}
				if (isBlackList(orginalTitle)) {
					return null;
				}
				chatPage = new ChatPage(PageConstant.CHAT_PAGE_ID, pageId, orginalTitle);
				chatPagesList.addElement(chatPage);
				if (isShow) {
					chatPage.setPreviousPageId(pageId);
					pages.addElement(chatPage);
					pagesSize = pages.size();
					currentPage = chatPage;
				}
				chatPage.run(this, isShow);
			}
		} catch (Exception e) {
		}
		return chatPage;
	}

	public boolean isBlackList(String name) {
		try {
			if (name != null && blackList != null) {
				int n = blackList.getSize();
				if (n > 0) {
					for (int i = n; --i >= 0;) {
						if (blackList.getItemAt(i).equals(name)) {
							return true;
						}
					}
				}
			}
		} catch (Exception e) {
		}
		return false;
	}

	public void removeChatPageBlacklist(String name) {
		removePage(PageConstant.CHAT_PAGE_ID, true);
		removeChatPageByUsername(name);
	}

	public ChatPage findChatPageByUsername(String name) {
		try {
			if (name != null) {
				int n = chatPagesList.size();
				if (n > 0) {
					for (int i = n; --i >= 0;) {
						ChatPage u = (ChatPage) chatPagesList.elementAt(i);
						if (u.getOrginalTitle().equals(name))
							return u;
					}
				}
			}
		} catch (Exception e) {
		}
		return null;
	}

	public void removeChatPageByUsername(String name) {
		try {
			if (name != null && chatPagesList != null) {
				int n = chatPagesList.size();
				if (n > 0) {
					for (int i = n; --i >= 0;) {
						ChatPage u = (ChatPage) chatPagesList.elementAt(i);
						if (u.getOrginalTitle().equals(name)) {
							chatPagesList.removeElementAt(i);
							return;
						}
					}
				}
			}
		} catch (Exception e) {
		}
	}

	public void removeChatListName(String name) {
		try {
			if (name != null && chatListName != null) {
				int n = chatListName.getSize();
				if (n > 0) {
					for (int i = n; --i >= 0;) {
						if (chatListName.getItemAt(i).equals(name)) {
							chatListName.removeItem(i);
							return;
						}
					}
				}
			}
		} catch (Exception e) {
		}
	}

	public synchronized void createChatListPage() {
		// System.out.println("Create chatlist Page");
		try {
			for (int i = pagesSize; --i >= 0;) {
				Page p = (Page) pages.elementAt(i);
				if (p instanceof ChatListPage) {
					int pageId = currentPage.getPageId();
					p.setPreviousPageId(pageId);
					currentPage = p;
					currentPage.show();
					return;
				}
			}
			int pageId = currentPage.getPageId();
			// System.out.println("Currentpageid " + pageId);
			if (chatListPage == null) {
				chatListPage = new ChatListPage(PageConstant.CHAT_LIST_PAGE_ID, pageId);
			}
			chatListPage.setPreviousPageId(pageId);
			pages.addElement(chatListPage);
			pagesSize = pages.size();
			currentPage = chatListPage;
			currentPage.run(this, true);
		} catch (Exception e) {
		}
	}

	public synchronized void createConferenceListPage() {
		// System.out.println("Create ConferenceList Page");
		try {
			for (int i = pagesSize; --i >= 0;) {
				Page p = (Page) pages.elementAt(i);
				if (p instanceof ConferenceListPage) {
					int pageId = currentPage.getPageId();
					p.setPreviousPageId(pageId);
					currentPage = p;
					currentPage.show();
					return;
				}
			}
			int pageId = currentPage.getPageId();
			// System.out.println("Currentpageid " + pageId);
			if (conferenceListPage == null) {
				conferenceListPage = new ConferenceListPage(PageConstant.CONFERENCE_LIST_PAGE_ID, pageId);
			}
			conferenceListPage.setPreviousPageId(pageId);
			pages.addElement(conferenceListPage);
			pagesSize = pages.size();
			currentPage = conferenceListPage;
			currentPage.run(this, true);
		} catch (Exception e) {
		}
	}

	public ConferencePage findConferencePageByTitle(String orginalTitle) {
		try {
			if (orginalTitle != null) {
				int n = conferenceListPages.size();
				if (n > 0) {
					for (int i = n; --i >= 0;) {
						ConferencePage u = (ConferencePage) conferenceListPages.elementAt(i);
						if (u.getOrginalTitle().equals(orginalTitle))
							return u;
					}
				}
			}
		} catch (Exception e) {
		}
		return null;
	}

	public synchronized void createConfirmJoinConferencePage() {
		// System.out.println("Create Confirm Join Conference Page");
		try {
			for (int i = pagesSize; --i >= 0;) {
				Page p = (Page) pages.elementAt(i);
				if (p instanceof ConfirmJoinConferencePage) {
					int pageId = currentPage.getPageId();
					p.setPreviousPageId(pageId);
					currentPage = p;
					currentPage.show();
					return;
				}
			}
			int pageId = currentPage.getPageId();
			// System.out.println("Currentpageid " + pageId);
			if (confirmJoinConferencePage == null) {
				confirmJoinConferencePage = new ConfirmJoinConferencePage(PageConstant.CONFIRM_JOIN_CONFERENCE_PAGE_ID, pageId);
			}
			confirmJoinConferencePage.setPreviousPageId(pageId);
			pages.addElement(confirmJoinConferencePage);
			pagesSize = pages.size();
			currentPage = confirmJoinConferencePage;
			currentPage.run(this, true);
		} catch (Exception e) {
		}
	}

	public synchronized void createBuddyPage() {
		// System.out.println("Create Buddy Page");
		try {
			for (int i = pagesSize; --i >= 0;) {
				Page p = (Page) pages.elementAt(i);
				if (p instanceof BuddyPage) {
					int pageId = currentPage.getPageId();
					p.setPreviousPageId(pageId);
					currentPage = p;
					currentPage.show();
					return;
				}
			}
			int pageId = currentPage.getPageId();
			if (pageId == PageConstant.BUDDY_PAGE_ID) {
				pageId = PageConstant.MAIN_PAGE_ID;
			}
			// System.out.println("Currentpageid " + pageId);
			if (buddyPage == null) {
				buddyPage = new BuddyPage(PageConstant.BUDDY_PAGE_ID, pageId);
				buddyPage.setPreviousPageId(pageId);
				pages.addElement(buddyPage);
				pagesSize = pages.size();
				currentPage = buddyPage;
				currentPage.run(this, true);
			} else {
				buddyPage.setPreviousPageId(pageId);
				pages.addElement(buddyPage);
				pagesSize = pages.size();
				currentPage = buddyPage;
				currentPage.show();
			}
		} catch (Exception e) {
		}
	}

	public synchronized void createYahooBuddyPage() {
		// System.out.println("Create yahooBuddyPage");
		try {
			for (int i = pagesSize; --i >= 0;) {
				Page p = (Page) pages.elementAt(i);
				if (p instanceof YahooBuddyPage) {
					int pageId = currentPage.getPageId();
					p.setPreviousPageId(pageId);
					currentPage = p;
					currentPage.show();
					return;
				}
			}
			int pageId = currentPage.getPageId();
			// System.out.println("Currentpageid " + pageId);
			if (pageId == PageConstant.YAHOO_BUDDY_PAGE_ID) {
				pageId = PageConstant.MAIN_PAGE_ID;
			}
			if (yahooBuddyPage == null) {
				yahooBuddyPage = new YahooBuddyPage(PageConstant.YAHOO_BUDDY_PAGE_ID, pageId);
				yahooBuddyPage.setPreviousPageId(pageId);
				pages.addElement(yahooBuddyPage);
				pagesSize = pages.size();
				currentPage = yahooBuddyPage;
				currentPage.run(this, true);
			} else {
				yahooBuddyPage.setPreviousPageId(pageId);
				pages.addElement(yahooBuddyPage);
				pagesSize = pages.size();
				currentPage = yahooBuddyPage;
				currentPage.show();
			}
		} catch (Exception e) {
		}
	}

	public synchronized void createBuddyInviteConferencePage() {
		// System.out.println("Create Buddy Invite Conference Page");
		try {
			for (int i = pagesSize; --i >= 0;) {
				Page p = (Page) pages.elementAt(i);
				if (p instanceof BuddyInviteConferencePage) {
					int pageId = currentPage.getPageId();
					p.setPreviousPageId(pageId);
					currentPage = p;
					currentPage.show();
					return;
				}
			}
			int pageId = currentPage.getPageId();
			// System.out.println("Currentpageid " + pageId);
			if (buddyInviteConferencePage == null) {
				buddyInviteConferencePage = new BuddyInviteConferencePage(PageConstant.BUDDY_INVITE_CONFERENCE_PAGE_ID, pageId);
			}
			buddyInviteConferencePage.setPreviousPageId(pageId);
			pages.addElement(buddyInviteConferencePage);
			pagesSize = pages.size();
			currentPage = buddyInviteConferencePage;
			currentPage.run(this, true);
		} catch (Exception e) {
		}
	}

	public synchronized void removeCurrentPage(boolean isShow) {
		if (currentPage != null) {
			removePage(currentPage.getPageId(), isShow);
		}
	}

	public synchronized boolean removePage(int pageId, boolean isShow) {
		try {
			if (pageId == -1) { // don't remove, just go back
				// come back here, always show
				// System.out.println("go to back page");
				Page page = getPageById(currentPage.getPreviousPageId());
				if (page != null) {
					currentPage = page;
					closeDialog(currentPage);
					page.show();
				}
				return false;
			}
			if (pagesSize > 0) { // remove specific page
				// System.out.println("close pageId 0: " + pageId);
				for (int i = pagesSize; --i >= 0;) {
					// System.out.println(i);
					Page page = (Page) pages.elementAt(i);
					if (page.getPageId() == pageId) {
						pages.removeElement(page);
						pagesSize = pages.size();
						// System.out.println("close pageId getPreviousPageId "
						// + currentPage.getPreviousPageId());
						// come back here
						Page prePage = getPageById(currentPage.getPreviousPageId());
						if (prePage == null) {
							// System.out.println("!!!!!Urgent error....................choose page main default");
							prePage = (Page) pages.elementAt(1);// error!!!,
																// always
																// goto main
																// page
						}
						// System.out.println("close pageId prePage");
						if (page != null) {
							currentPage = prePage;
							closeDialog(currentPage);
							if (isShow) {
								prePage.show();
							}
						}
						// System.out.println("close pageId 3 done!!!");
						return true;
					}
				}
			}
		} catch (Exception e) {
		}
		return false;
	}

	public synchronized Page showViewerPage(byte[] data) {
		// System.out.println("Create showViewerPage Page " + data.length);
		for (int i = pagesSize; --i >= 0;) {
			Page p = (Page) pages.elementAt(i);
			if (p instanceof PhotoViewerPage) {
				int pageId = currentPage.getPageId();
				p.setPreviousPageId(pageId);
				currentPage = p;
				currentPage.show();
				return currentPage;
			}
		}
		int pageId = currentPage.getPageId();
		// System.out.println("Currentpageid " + pageId);
		if (photoViewerPage == null) {
			photoViewerPage = new PhotoViewerPage(PageConstant.PHOTO_VIEWER_PAGE_ID, pageId);
		}
		photoViewerPage.setData(data);
		photoViewerPage.setPreviousPageId(pageId);
		pages.addElement(photoViewerPage);
		pagesSize = pages.size();
		currentPage = photoViewerPage;
		currentPage.run(this, true);
		return currentPage;
	}

	public Page clearAllPage() {
		isBegin = false;
		currentPage = (Page) pages.elementAt(0);
		closeDialog(currentPage);
		currentPage.show();
		// for (int i = pagesSize; --i > 0;) {
		// Page page = (Page) pages.elementAt(i);
		// page.cleanup();
		// pages.removeElementAt(i);
		// }
		// pagesSize = pages.size();
		// System.out.println("clearAllPage done");
		return currentPage;
	}

	public synchronized Page getCurrentPage() {
		return currentPage;
	}

	public synchronized int getCurrentPageId() {
		if (currentPage == null) {
			return -1;
		}
		return currentPage.getPageId();
	}

	// ==========================================Dialogs
	private void showSmileyDialog() {
		if (smileyDialog != null) {
			// int bottom = 27;
			// int top = Display.getInstance().getDisplayHeight() - 100;
			// int left = 16;
			// int right = 16;
			// smileyDialog.show(top, bottom, left, right, false, true);

			smileyDialog.showPacked(BorderLayout.SOUTH, true);
		}
	}

	// public void showProcessingDialog() {
	// final Slider slider = new Slider();
	// slider.setRenderPercentageOnTop(true);
	// slider.setRenderValueOnTop(true);
	//
	// new Thread() {
	// private boolean dir = true;
	// private int val = 0;
	//
	// public void run() {
	// try {
	// sleep(1000);
	// while (Display.getInstance().getCurrent() == AvatarPage.instance) {
	// sleep(100);
	// slider.setProgress(val);
	// if (dir) {
	// if (val > 100) {
	// dir = false;
	// }
	// val++;
	// } else {
	// if (val < 1) {
	// dir = true;
	// }
	// val--;
	// }
	// }
	// } catch (InterruptedException ex) {
	// ex.printStackTrace();
	// }
	// }
	// }.start();
	//
	// Command okCommand = new Command(Language.CLOSE[ClientConstant.LANGUAGE]);
	// Dialog.show(Language.PLEASE_WAIT[ClientConstant.LANGUAGE], slider, new
	// Command[] { okCommand });
	// }

	public synchronized void showWaitingDialog() {
		// dialog = new
		// ProgressDialog(Language.PLEASE_WAIT[ClientConstant.LANGUAGE]);
		// dialog.showModeless();
		// dialog.show();
		//
		// // Dialog.show("", container, null, Dialog.TYPE_INFO, null, 5000);
		// Command okCommand = new
		// Command(Language.CLOSE[ClientConstant.LANGUAGE]);
		// Dialog.show(Language.PLEASE_WAIT[ClientConstant.LANGUAGE],
		// Language.PLEASE_WAIT[ClientConstant.LANGUAGE], okCommand, new
		// Command[] { okCommand }, Dialog.TYPE_INFO, null, 0, null);
		try {
			if (waitingNoticePainter == null) {
				waitingNoticePainter = new WaitingNoticePainter(200, "Vui lòng chờ");
			}
			// System.out.println("==================open waiting");
			Form f = Display.getInstance().getCurrent();
			if (f != null) {
				waitingNoticePainter.setParent(f);
				PainterChain.installGlassPane(f, waitingNoticePainter);
				f.registerAnimated(waitingNoticePainter);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void showInfoDialog(String title, String content) {
		// closeDialog();
		// currentPage.show();
		// try {
		// Thread.sleep(1000);
		// } catch (InterruptedException e) {
		// e.printStackTrace();
		// }
		// Command command = Dialog.show(title, content,
		// Language.CLOSE[ClientConstant.LANGUAGE], null);
		if (infoDialog == null) {
			infoDialog = new Dialog(title);
			infoDialog.getTitleStyle().setFgColor(0xff0000);
			info = new TextArea(content);
			info.setEditable(false);
			info.setFocusable(false);
			info.getStyle().setAlignment(Component.CENTER);
			info.getStyle().setBgColor(0xffffff);
			info.getStyle().setFgColor(0);
			info.getStyle().setPadding(Component.TOP, 0);
			info.getStyle().setMargin(Component.TOP, 0);
			info.getStyle().setPadding(Component.LEFT, 0);
			info.getStyle().setMargin(Component.LEFT, 0);
			info.getStyle().setPadding(Component.BOTTOM, 0);
			info.getStyle().setMargin(Component.BOTTOM, 0);
			info.getStyle().setPadding(Component.RIGHT, 0);
			info.getStyle().setMargin(Component.RIGHT, 0);
			infoDialog.getContentPane().addComponent(info);
			Command okCommand = new Command(Language.CLOSE[ClientConstant.LANGUAGE]);
			infoDialog.addCommand(okCommand);
			Border border = Border.createRoundBorder(4, 4, 0xffffff);
			Dialog.setDialogTitleCompatibilityMode(true);
			infoDialog.getContentPane().getUnselectedStyle().setBorder(border);
			infoDialog.getContentPane().getUnselectedStyle().setBorder(border);
			Dialog.setDialogTitleCompatibilityMode(false);

		}
		Form current = Display.getInstance().getCurrent();
		if (current != null) {
			closeDialog(current);
		}
		info.setText(content);
		infoDialog.setTitle(title);
		infoDialog.showPacked(BorderLayout.CENTER, true);

		// Dialog.show(title, content, Language.CLOSE[ClientConstant.LANGUAGE],
		// null);
	}

	public void closeDialog(Form current) {
		try {
			if (current == null) {
				current = getCurrentPage();
			}
			// System.out.println("==================close waiting");
			if (current != null) {
				current.deregisterAnimated(waitingNoticePainter);
				PainterChain.removeGlassPane(current, waitingNoticePainter);
			}
		} catch (Exception e) {
		}
	}

	public void closeDialog() {
		try {
			Page current = getCurrentPage();
			// System.out.println("==================close waiting");
			if (current != null) {
				current.deregisterAnimated(waitingNoticePainter);
				PainterChain.removeGlassPane(current, waitingNoticePainter);
			}
		} catch (Exception e) {
		}
	}

	public void alert(String title, String content, boolean isForever) {
		Alert alert = new Alert(title);
		alert.setString(content);
		if (isForever)
			alert.setTimeout(Alert.FOREVER);
		javax.microedition.lcdui.Display.getDisplay(BeU.instance).setCurrent(alert);
	}

	// ==========================================Listener

	public void onMagicPageCheckSumComing(int pageId, int checkSum) {
		//		System.out.println("onMagicPageCheckSumComing pageId " + pageId + " checkSum " + checkSum);
		int cs = loadMagicCheckSumFromRMS(pageId);
		//		System.out.println("cs = " + cs);
		if (cs == -1 || cs != checkSum) {
			//			System.out.println("Hix!!! Page not checkSum:(");
			BeUSession.requestMagicPage(pageId);
			// System.out.println("HMM, Page " + pageId + " NOT CACHE");
		} else {
			// System.out.println("WELL DONE: Page " + pageId + " IS CACHED");
			if (selectPage(pageId) == null) {
				//				System.out.println("Hix!!! Page in RMS!!! Normal");
				byte[] executeCode = loadMagicPageSumFromRMS(pageId);
				ByteArrayInputStream b = new ByteArrayInputStream(executeCode);
				MagicExecutor.deCompilePage(b, true);
			} else {
				//				System.out.println("Wom!!! Page in RAM!!! FASTEST");
			}
		}
	}

	public void onFriendListComing(int checkSum, DefaultListModel buddies) {
		// System.out.println("onFriendListComing " + buddies.size() +
		// " checkSum " + checkSum);
		friendListModel = buddies;
		saveBuddyToRMS(buddies, username);
		saveCheckSumToRMS(checkSum, username);
		if (buddyPage == null) {
			buddyPage = new BuddyPage(PageConstant.BUDDY_PAGE_ID, -1);
			buddyPage.run(this, false);
		}
		// addBuddyPage();
	}

	public void onBuddyInfoComing(Buddy buddy) {
//		System.out.println("onBuddyInfoComing " + buddy.getUsername());
		if (friendListModel != null) {
			int n = friendListModel.getSize();
			for (int i = 0; i < n; i++) {
				Buddy b = (Buddy) friendListModel.getItemAt(i);
				if (b != null && b.getUserId() == buddy.getUserId()) {
					friendListModel.removeItem(i);
					break;
				}
			}
			friendListModel.addItem(buddy);
		}
		// addBuddyPage();
	}

	public void onBlackListComing(DefaultListModel bl) {
		// addBuddyPage();
		blackList = bl;
	}

	public void onPopupMessageComing(final String content, final Form f) {
		showSystemMessage(content, f, (byte) -1);
	}

	public void onHandshakeChatMessageComing(String from, String content) {
		// first handshake
		Page cur = getCurrentPage();
		if (cur instanceof ChatPage) {
			ChatPage p = (ChatPage) currentPage;
			if (p.getOrginalTitle().equals(from)) {
				p.addItems(from, content);
				return;
			}
		}
		ChatPage page = addChatPage(from, false, true);
		if (page != null) {
			page.addItems(from, content);
			addOrUpdateChatListModel(from);
			showSystemMessage(from + " đang chat", null, (byte) 1);
		}
	}

	public void onBuzzComing(String from) {
		Page cur = getCurrentPage();
		if (cur instanceof ChatPage) {
			ChatPage p = (ChatPage) currentPage;
			if (p.getOrginalTitle().equals(from)) {
				p.addItems(from, "Hù!");
				startVibrate();
				playSound();
				return;
			}
		}
		ChatPage page = addChatPage(from, false, true);
		if (page != null) {
			page.addItems(from, "Hù!");
			addOrUpdateChatListModel(from);
			showSystemMessage(from + " hù!", null, (byte) 1);
			startVibrate();
			playSound();
		}
	}

	public void onChatMessageComing(long userId, String msgChat) {
		// System.out.println("Not yet implement");
	}

	public void onUserIdComing(String name, long id) {
		//		String temp = findUsernameById(id);
		//		if (temp == null) {
		//			UserInfo u = new UserInfo();
		//			u.userId = id;
		//			u.username = name;
		//			userInfo.addElement(u);
		//		}
	}

	public String findUsernameById(long id) {
		//		int n = userInfo.size();
		//		for (int i = n; --i >= 0;) {
		//			UserInfo u = (UserInfo) userInfo.elementAt(i);
		//			if (u.userId == id)
		//				return u.username;
		//		}
		return null;
	}

	public long findIdByUsername(String username) {
		//		int n = userInfo.size();
		//		for (int i = n; --i >= 0;) {
		//			UserInfo u = (UserInfo) userInfo.elementAt(i);
		//			if (u.username.equals(username))
		//				return u.userId;
		//		}
		return -1;
	}

	public void addOrUpdateChatListModel(String username) {
		// System.out.println("Update chatlistmodel " + username);
		int n = chatListName.getSize();
		if (n > 0) {
			for (int i = 0; i < n; i++) {
				if (chatListName.getItemAt(i).equals(username)) {
					return;
				}
			}
		}
		chatListName.addItem(username);
	}

	public void onChangeStatusComing(String username, byte status) {
		String text = null;
		if (status == ClientConstant.ONLINE) {
			text = username + Language.USER_ONLINE[ClientConstant.LANGUAGE];
		} else {
			text = username + Language.USER_OFF_INVI[ClientConstant.LANGUAGE];
		}
		// System.out.println("onChangeStatusComing: " + text);
		showSystemMessage(text, null, status);
		// first handshake
		Page cur = getCurrentPage();
		if (cur instanceof ChatPage) {
			ChatPage p = (ChatPage) currentPage;
			if (p.getOrginalTitle().equals(username)) {
				p.addItems(username, text);
				return;
			}
		}
		ChatPage page = addChatPage(username, false, false);
		if (page != null) {
			page.addItems(username, text);
		}
		updateStatusFriendlist(username, status);
	}

	// =====================================HELPER
	public void showNextChatPage(ChatPage chatPage) {
		int n = chatPagesList.size();
		int index = chatPagesList.indexOf(chatPage);
		// System.out.println("showNextChatPage " + n + " index " + index);
		if (index < n - 1) {
			ChatPage c = (ChatPage) chatPagesList.elementAt(index + 1);
			addPage(c);
			c.show();
		}
	}

	public void showPreviousChatPage(ChatPage chatPage) {
		// int n = chatPagesList.size();
		int index = chatPagesList.indexOf(chatPage);
		// System.out.println("showPreviousChatPage " + n + " index " + index);
		if (index > 0) {
			ChatPage c = (ChatPage) chatPagesList.elementAt(index - 1);
			addPage(c);
			c.show();
		}
	}

	public void showNextConferencePage(ConferencePage conferencePage) {
		int n = conferenceListPages.size();
		int index = conferenceListPages.indexOf(conferencePage);
		// System.out.println("showNextconferencePage " + n + " index " +
		// index);
		if (index < n - 1) {
			ConferencePage c = (ConferencePage) conferenceListPages.elementAt(index + 1);
			addPage(c);
			c.show();
		}
	}

	public void showPreviousConferencePage(ConferencePage conferencePage) {
		// int n = conferenceListPages.size();
		int index = conferenceListPages.indexOf(conferencePage);
		// System.out.println("showPreviousconferencePage " + n + " index " +
		// index);
		if (index > 0) {
			ConferencePage c = (ConferencePage) conferenceListPages.elementAt(index - 1);
			addPage(c);
			c.show();
		}
	}

	public void startVibrate() {
		if (!isVibrate)
			return;
		javax.microedition.lcdui.Display.getDisplay(BeU.instance).vibrate(500);
	}

	public void playSound() {
		if (isMute) {
			return;
		}
		try {
			resetMusicPlayer();
			/*
			 * CameraCanvas.getInstance().free();
			 * VideoCanvas.getInstanse().stop();
			 */
			player = Manager.createPlayer("".getClass().getResourceAsStream("/b.mid"), "audio/midi");
			// player = Manager.createPlayer(dingInputStream, "audio/midi");
			player.realize();
			((VolumeControl) player.getControl("VolumeControl")).setLevel(100);
			player.prefetch();
		} catch (Exception e) {
			// System.out.println("wwwwwww");
			bMuzikDisable = true;
			// e.printStackTrace();
		}

		if (bMuzikDisable)
			return;
		try {
			player.start();
		} catch (Exception e) {
			// System.out.println("qqqqqq");
			// e.printStackTrace();
		}
	}

	public static void resetMusicPlayer() {
		if (player != null) {
			try {
				player.stop();
			} catch (Exception e) {
			}
			player.deallocate();
			player = null;
		}
		System.gc();
	}

	public void sendSMS(final String data, final String to) {
		// System.out.println("data = "+data+"; to = "+to);
		final String address = to;
		// MainFrame.getInstance().startDlg("Sending SMS", null, null, null);
		new Thread(new Runnable() {
			public void run() {
				try {
					MessageConnection smsconn = null;
					smsconn = (MessageConnection) Connector.open(address);
					TextMessage txtmessage = (TextMessage) smsconn.newMessage(MessageConnection.TEXT_MESSAGE);
					txtmessage.setAddress(address);
					txtmessage.setPayloadText(data);
					smsconn.send(txtmessage);
					Core.getInstance().showInfoDialog(Language.INFO[ClientConstant.LANGUAGE], Language.SEND_SMS_SUCCESS[ClientConstant.LANGUAGE]);
				} catch (Exception e) {
					Core.getInstance().showInfoDialog(Language.ERROR[ClientConstant.LANGUAGE], Language.SEND_SMS_FAIL[ClientConstant.LANGUAGE]);
				}
			}
		}).start();
	}

	private void doActionAddBlacklist(String victim) {
		BeUSession.addBlackList(victim);
		blackList.addItem(victim);
		removeBuddy(victim);
		removeChatPageBlacklist(victim);
		removeChatListName(victim);
	}

	private synchronized void showSystemMessage(String text, Form f, byte status) {
		if (f == null) {
			f = Display.getInstance().getCurrent();
		}
		statusNotice = new StatusNoticePainter(50, text, status, f);
		// statusNotice.setParent(f, status);
		PainterChain.installGlassPane(f, statusNotice);
		f.registerAnimated(statusNotice);
	}

	private void closeApp() {
		friendListModel = null;
	}

	public final void sendFileRequest() {
		try {
			// System.out.println("sendFileRequest ");
			final FileConnector fileConnector = FileConnector.getConnector();
			final FileBrowser fb = FileBrowser.getInstance();
			fb.extraAction = new IAction() {// extraAction is paired with
											// cmdOpen of MAIN_TASK_OPEN
				public void perform() {
					final String fileNameChosen = fb.getFilePath(true);// fileName
																		// with
																		// path

					if (FileBrowser.isFileNameValid(fileNameChosen)) {
						// if
						// (!MainFrame.isSupportedFile(fileNameChosen.toLowerCase(),
						// true)) {
						// MainFrame.getInstance().alert(T.vitalk,
						// T.fileNotSupported(), true);
						// return;
						// }
						Core.getInstance().getCurrentPage().show();
						int fileSize = fileConnector.getFileSize(fileNameChosen);

						if (fileSize < 0)
							Core.getInstance().showInfoDialog(Language.ERROR[ClientConstant.LANGUAGE], Language.READ_FILE_ERROR[ClientConstant.LANGUAGE]);
						else {
							readFileToDoAction(false);
						}
						// if (fileSize > 30000)
						// startDlgFileTooLarge_ToSend(fileSize);
						// else readFileToOpen();
					}
				}
			};
			fb.show(Language.CHOOSE_FILE_TYPE[ClientConstant.LANGUAGE], FileBrowser.MAIN_TASK_OPEN);// ,
			// FileBrowser.BROWSE_TYPE_MEMORY);

		} catch (ClassNotFoundException e) {
			Core.getInstance().getCurrentPage().show();
			Core.getInstance().showInfoDialog(Language.ERROR[ClientConstant.LANGUAGE], Language.PHONE_SUPPORT_ERROR[ClientConstant.LANGUAGE]);
		} catch (Exception ex) {
			Core.getInstance().getCurrentPage().show();
		}
	}

	public static boolean isSupportedImageFile(String fileName) {
		fileName = fileName.toLowerCase();
		String[] supportedExt = { ".png" };
		for (int i = 0; i < supportedExt.length; i++) {
			if (fileName.endsWith(supportedExt[i]))
				return true;
		}
		return false;
	}

	public final void readFileToDoAction(final boolean isOpenAction) {
		new Thread(new Runnable() {
			public void run() {
				// System.out.println("readFileToDoAction:  va has: isOpenAction   :  "+
				// isOpenAction);
				FileBrowser fb = FileBrowser.getInstance();
				byte[] fileData = null;
				try {
					FileConnector fileConnector = FileConnector.getConnector();
					fileData = fileConnector.readFile(fb.getFilePath(true));
				} catch (ClassNotFoundException e) {
					Core.getInstance().showInfoDialog(Language.ERROR[ClientConstant.LANGUAGE], Language.PHONE_SUPPORT_ERROR[ClientConstant.LANGUAGE]);
					return;
				}
				if ((fileData == null) || (fileData.length == 0)) { // show
																	// message
																	// read file
																	// has 0Kbs
					Core.getInstance().showInfoDialog(Language.ERROR[ClientConstant.LANGUAGE], Language.READ_FILE_ERROR[ClientConstant.LANGUAGE]);
					return;
				}
				if (isOpenAction) {
					// k.q
					// System.out.println("readFileToDoAction va isOpenAction");

					/*
					 * if (fb.getFilePath(false).toLowerCase().endsWith(".png"))
					 * {// CAMERA_CAPTURED || PNG
					 * MainFrame.instance.fotoViewerPage.setData(fileData, null,
					 * "Foto", true); }else
					 * if(fb.getFilePath(false).toLowerCase().endsWith(".mp3")
					 * || fb.getFilePath(false).toLowerCase().endsWith(".3gp")||
					 * fb.getFilePath(false).toLowerCase().endsWith(".wav")||
					 * fb.getFilePath(false).toLowerCase().endsWith(".mp4")||
					 * fb.getFilePath(false).toLowerCase().endsWith(".mpg")) {
					 * MainFrame.instance.fotoViewerPage.autoPlayVideo(fileData,
					 * null, "Video", true, fb.getFilePath(true)); //k.q add }
					 */
					// k.q modified
					/*
					 * String fileName = fb.getFilePath(false);
					 * if(MainFrame.isSupportedImageFile(fileName)) {
					 * MainFrame.instance.fotoViewerPage.setData(fileData, null,
					 * "Foto", true); }else { MainFrame.getInstance().show();
					 * MainFrame.getInstance().startOKDlg(T.fileNotOpen()); }
					 */

					// MainFrame.instance.fotoViewerPage.setData(fileData, null,
					// "Foto", true);

					/*
					 * if(MainFrame.isSupportVideoFile(fileName)) {
					 * MainFrame.instance.fotoViewerPage.autoPlayVideo(fileData,
					 * null, fileName, true, fb.getFilePath(true)); }
					 */
				} else {
					// imgData = fileData;
					// doSending();
					BeUSession.requestUploadImage(fileData);
				}
			}
		}).start();
	}

	// ///////////////////////////////////////////////////////////////
	// MIME Types
	// ///////////////////////////////////////////////////////////////
	public static final String MIMETYPE_TEXT_PLAIN = "text/plain";
	public static final String MIMETYPE_TEXT_XML = "text/xml";
	public static final String MIMETYPE_APP_XML = "application/xml";
	public static final String MIMETYPE_IMAGE_PNG = "image/png";

	// ///////////////////////////////////////////////////////////////
	// HTTP Contants
	// ///////////////////////////////////////////////////////////////
	private static final String HTTPHDR_ACCEPT = "Accept";

	private static final String HTTPHDR_USER_AGENT = "User-Agent";
	private static String HTTPHDR_USER_AGENT_VALUE;

	private static final String HTTPHDR_CONNECTION = "Connection";
	private static final String HTTPHDR_CONNECTION_CLOSE = "close";

	private static final String HTTPHDR_CACHE_CONTROL = "Cache-Control";
	private static final String HTTPHDR_CACHE_CONTROL_NOTRANSFORM = "no-transform";
	private static final String HTTPHDR_CONTENT_LEN = "Content-Length";

	static {
		// Retrieve the underlying profile and configuration for User Agent
		String p = System.getProperty("microedition.profiles");
		String c = System.getProperty("microedition.configuration");
		HTTPHDR_USER_AGENT_VALUE = "Profile/" + p + " Configuration/" + c;
	}

	/**
	 * Gets a Resource over HTTP, returing an <code>DataInputStream</code> to it
	 * 
	 * @param uri
	 *            is the URI to use to get the resource to retrieve
	 * @pararm mimeType is the (possible) mime type(s) of the resource to
	 *         retrieve
	 * 
	 * @return an <code>DataInputStream</code> for the input resource
	 * 
	 * @throws <code>IOException</code> is thrown if an error is encountered
	 */
	static public DataInputStream getResourceOverHTTP(String uri, String mimeType) throws IOException {

		HttpConnection connection = null;
		IOException ioException = null;
		DataInputStream is = null;

		try {
			connection = (HttpConnection) Connector.open(uri, Connector.READ, true);

			connection.setRequestMethod(HttpConnection.GET);

			connection.setRequestProperty(HTTPHDR_ACCEPT, mimeType);

			connection.setRequestProperty(HTTPHDR_USER_AGENT, HTTPHDR_USER_AGENT_VALUE);

			connection.setRequestProperty(HTTPHDR_CONNECTION, HTTPHDR_CONNECTION_CLOSE);

			connection.setRequestProperty(HTTPHDR_CACHE_CONTROL, HTTPHDR_CACHE_CONTROL_NOTRANSFORM);

			connection.setRequestProperty(HTTPHDR_CONTENT_LEN, String.valueOf("0"));

			// ////////////////////////////////////
			// Send GET, receive initial response
			// ////////////////////////////////////
			int rc = connection.getResponseCode();

			// ///////////////////////////////////////////////////////
			// If an HTTP error was encountered, stop, indicate error
			// ///////////////////////////////////////////////////////
			if (rc != HttpConnection.HTTP_OK) {
				// Log error, throw IO exception
				ioException = new IOException("Http Error, response Code is " + rc);
				throw ioException;
			}
			is = connection.openDataInputStream();
		} catch (IOException ioe) {
			// Log error, throw IO exception
			throw ioe; // Propagate the IO Exception
		} finally {
			if (connection != null) {
				connection.close();
			}
		}
		return is;
	}

	// ======================================PLAYER LISTENER
	private Player musicPlayerA;
	private Player musicPlayerB;
	private InputStream inputStreamA;
	private InputStream inputStreamB;
	private VolumeControl volumeControl;
	public int currentSongId;
	private int currentChunkId;
	private Thread t;

	public void preparePlaying(byte[] firstChunk, int chunkId, int songId) {
		try {
			if (currentChunkId % 2 == 0) {
				if (inputStreamB != null) {
					inputStreamB.close();
					inputStreamB = null;
				}
				inputStreamA = new ByteArrayInputStream(firstChunk);
				try {
					musicPlayerA = Manager.createPlayer(inputStreamA, "audio/x-wav");
					// musicPlayerA = Manager.createPlayer(inputStream,
					// "audio/mpeg");
				} catch (Exception e) {
					e.printStackTrace();
					try {
						musicPlayerA = Manager.createPlayer(inputStreamA, "audio/mp3");
					} catch (Exception e2) {
						e.printStackTrace();
					}
				}
				musicPlayerA.prefetch();
				musicPlayerA.addPlayerListener(this);

				// if (loopMusic) {
				// // use the loop count method for infinite looping
				// playerA.setLoopCount(-1);
				// }

				volumeControl = (VolumeControl) musicPlayerA.getControl("VolumeControl");
				volumeControl.setLevel(100);

				musicPlayerA.start();
			} else {
				if (inputStreamA != null) {
					inputStreamA.close();
					inputStreamA = null;
				}
				inputStreamB = new ByteArrayInputStream(firstChunk);
				try {
					musicPlayerB = Manager.createPlayer(inputStreamB, "audio/x-wav");
					// musicPlayerB = Manager.createPlayer(inputStream,
					// "audio/mpeg");
				} catch (Exception e) {
					e.printStackTrace();
					try {
						musicPlayerB = Manager.createPlayer(inputStreamB, "audio/mp3");
					} catch (Exception e2) {
						e.printStackTrace();
					}
				}
				musicPlayerB.prefetch();
				musicPlayerB.addPlayerListener(this);

				// if (loopMusic) {
				// // use the loop count method for infinite looping
				// playerA.setLoopCount(-1);
				// }

				volumeControl = (VolumeControl) musicPlayerB.getControl("VolumeControl");
				volumeControl.setLevel(100);

				musicPlayerB.start();
			}
			currentSongId = songId;
			currentChunkId = chunkId;
			t = new Thread(new Runnable() {

				public void run() {
					while (currentChunkId != -1) {
						updateBufferSong();
						try {
							Thread.sleep(1000);
						} catch (Exception e) {
						}
					}
				}
			});
			t.start();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void playerUpdate(Player player, String event, Object eventData) {
		try {
			if (event == PlayerListener.END_OF_MEDIA) {
				player.stop();
				player.deallocate();
				player.close();
				player = null;
				if (currentChunkId % 2 == 0) {
					// System.out.println("####################playerUpdate musicPlayerB");
					musicPlayerB.start();
					musicPlayerA = null;
				} else {
					// System.out.println("####################playerUpdate musicPlayerA");
					musicPlayerA.start();
					musicPlayerB = null;
				}

				// if (currentPlayerIndex % 2 != 0) {
				// System.out.println("####################playerUpdate musicPlayerB");
				// if (songData.size() > 0) {
				// inputStream = new ByteArrayInputStream((byte[])
				// songData.elementAt(0));
				// try {
				// musicPlayerB = Manager.createPlayer(inputStream,
				// "audio/x-wav");
				// // musicPlayerB = Manager.createPlayer(inputStream,
				// "audio/mpeg");
				// } catch (Exception e) {
				// e.printStackTrace();
				// try {
				// musicPlayerB = Manager.createPlayer(inputStream,
				// "audio/mp3");
				// } catch (Exception e2) {
				// e.printStackTrace();
				// }
				// }
				// musicPlayerB.addPlayerListener(this);
				// // volumeControl = (VolumeControl)
				// musicPlayerB.getControl("VolumeControl");
				// // volumeControl.setLevel(100);
				// musicPlayerB.realize();
				// musicPlayerB.prefetch();
				// musicPlayerB.start();
				// }
				// } else {
				// System.out.println("####################playerUpdate musicPlayerA");
				// if (songData.size() > 0) {
				// inputStream = new ByteArrayInputStream((byte[])
				// songData.elementAt(0));
				// try {
				// musicPlayerA = Manager.createPlayer(inputStream,
				// "audio/x-wav");
				// // musicPlayerA = Manager.createPlayer(inputStream,
				// "audio/mpeg");
				// } catch (Exception e) {
				// e.printStackTrace();
				// try {
				// musicPlayerA = Manager.createPlayer(inputStream,
				// "audio/mp3");
				// } catch (Exception e2) {
				// e.printStackTrace();
				// }
				// }
				// musicPlayerA.addPlayerListener(this);
				// // volumeControl = (VolumeControl)
				// musicPlayerA.getControl("VolumeControl");
				// // volumeControl.setLevel(100);
				// musicPlayerA.realize();
				// musicPlayerA.prefetch();
				// musicPlayerA.start();
				// }
				// }
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	// ======================================LISTENER
	private void updateStatusFriendlist(String username, byte status) {
		if (friendListModel != null) {
			int n = friendListModel.getSize();
			for (int i = 0; i < n; i++) {
				Buddy buddy = (Buddy) friendListModel.getItemAt(i);
				if (buddy != null && buddy.getUsername().equals(username)) {
					buddy.setStatus(status);
					// buddy.setStatusText(blast);
					return;
				}
			}
		}
	}

	private void updateBuddyInfoYahoo(String username, byte status, String statusText) {
		if (yahooFriendListModel != null) {
			int n = yahooFriendListModel.getSize();
			for (int i = 0; i < n; i++) {
				Buddy buddy = (Buddy) yahooFriendListModel.getItemAt(i);
				if (buddy != null && buddy.getUsername().equals(username)) {
					buddy.setStatus(status);
					buddy.setStatusText(statusText);
					return;
				}
			}
		}
	}

	private void removeBuddy(String username) {
		if (friendListModel != null) {
			int n = friendListModel.getSize();
			for (int i = 0; i < n; i++) {
				Buddy buddy = (Buddy) friendListModel.getItemAt(i);
				if (buddy != null && buddy.getUsername().equals(username)) {
					friendListModel.removeItem(i);
					return;
				}
			}
		}
	}

	public void addInviteConference(String username) {
		int n = inviteConferenceList.size();
		for (int i = 0; i < n; i++) {
			if (inviteConferenceList.elementAt(i).equals(username)) {
				return;
			}
		}
		inviteConferenceList.addElement(username);
	}

	public void removeInviteConference(String username) {
		if (inviteConferenceList != null) {
			int n = inviteConferenceList.size();
			for (int i = 0; i < n; i++) {
				if (inviteConferenceList.elementAt(i).equals(username)) {
					inviteConferenceList.removeElementAt(i);
					return;
				}
			}
		}
	}

	public void onAskJoinConferenceComing(long conferenceId, String inviter, String roomName) {
		InviteConference ic = new InviteConference();
		ic.confId = conferenceId;
		ic.actor = inviter;
		ic.conferenceName = roomName;
		waitingConfirmConference.addElement(ic);
		showSystemMessage(inviter + " mời bạn chat nhóm", null, (byte) 1);
	}

	public void removeInviteLetter(long conferenceId) {
		if (inviteConferenceList != null) {
			int n = waitingConfirmConference.size();
			for (int i = 0; i < n; i++) {
				InviteConference ic = (InviteConference) waitingConfirmConference.elementAt(i);
				if (ic.confId == conferenceId) {
					waitingConfirmConference.removeElementAt(i);
					return;
				}
			}
		}
	}

	public void joinConference(long conferenceId, String username, boolean result) {
		// System.out.println("joinConference " + username + " conferenceId " +
		// conferenceId + " " + result);
		int n = conferenceListPages.size();
		for (int i = 0; i < n; i++) {
			ConferencePage conferencePage = (ConferencePage) conferenceListPages.elementAt(i);
			if (conferencePage != null && conferencePage.getConferenceId() == conferenceId) {
				conferencePage.addItems(username, username + Language.SOMEONE_JOIN_CONFERENCE[ClientConstant.LANGUAGE]);
				return;
			}
		}
	}

	public void leaveConference(long conferenceId, String username) {
		// System.out.println("leaveConference " + username + " conferenceId " +
		// conferenceId);
		int n = conferenceListPages.size();
		for (int i = 0; i < n; i++) {
			ConferencePage conferencePage = (ConferencePage) conferenceListPages.elementAt(i);
			if (conferencePage != null && conferencePage.getConferenceId() == conferenceId) {
				conferencePage.addItems(username, username + Language.SOMEONE_LEFT_CONFERENCE[ClientConstant.LANGUAGE]);
				return;
			}
		}
	}

	public void onBeKickConference(long conferenceId, String roomName) {
		// System.out.println("onBeKickConference " + username +
		// " conferenceId " + conferenceId);
		removeConference(conferenceId);
		showInfoDialog(Language.INFO[ClientConstant.LANGUAGE], "Bạn đã bị đá khỏi phòng " + roomName);
	}

	public void chatConference(long conferenceId, String username, String content) {
		int n = conferenceListPages.size();
		for (int i = 0; i < n; i++) {
			ConferencePage conferencePage = (ConferencePage) conferenceListPages.elementAt(i);
			if (conferencePage != null && conferencePage.getConferenceId() == conferenceId) {
				if (!username.equals(this.username)) {
					conferencePage.addItems(username, content);
				}
				return;
			}
		}
	}

	public void removeConference(long conferenceId) {
		int n = conferenceListPages.size();
		ConferencePage confPage = null;
		for (int i = 0; i < n; i++) {
			confPage = (ConferencePage) conferenceListPages.elementAt(i);
			if (confPage != null && confPage.getConferenceId() == conferenceId) {
				conferenceListPages.removeElementAt(i);
				break;
			}
		}
		if (confPage != null) {
			int m = conferenceListName.getSize();
			for (int i = 0; i < m; i++) {
				if (conferenceListName.getItemAt(i).equals(confPage.getOrginalTitle())) {
					conferenceListName.removeItem(i);
					return;
				}
			}
		}
	}

	public void onUploadFileResult(long sessionId, String url) {
	}

	public void onImageResultComing(String url, byte[] imageData) {
	}

	public void onFirstChunkAudioComing(int chunkId, byte[] chunkData, int songId, int totalChunk) {
		// System.out.println("onFirstChunkAudioComing songId " + songId +
		// " chunkId " + chunkId + " totalChunk " + totalChunk + " length " +
		// chunkData.length);
		preparePlaying(chunkData, chunkId, songId);
	}

	public void onNextChunkAudioComing(int chunkId, byte[] chunkData, int songId) {
		// System.out.println("onNextChunkAudioComing songId " + songId +
		// " chunkId " + chunkId + " length " + chunkData.length);
		try {
			if (songId == currentSongId) {
				if (chunkId % 2 != 0) {
					inputStreamB.close();
					inputStreamB = null;
					inputStreamA = new ByteArrayInputStream(chunkData);
					if (musicPlayerA == null) {
						// System.out.println("Yeah! musicPlayerA is null");
					}
					try {
						musicPlayerA = Manager.createPlayer(inputStreamA, "audio/x-wav");
						// musicPlayerA = Manager.createPlayer(inputStream,
						// "audio/mpeg");
					} catch (Exception e) {
						e.printStackTrace();
						try {
							musicPlayerA = Manager.createPlayer(inputStreamA, "audio/mp3");
						} catch (Exception e2) {
							e.printStackTrace();
						}
					}
					musicPlayerA.prefetch();
					musicPlayerA.addPlayerListener(this);

					// if (loopMusic) {
					// // use the loop count method for infinite looping
					// playerA.setLoopCount(-1);
					// }

					// volumeControl = (VolumeControl)
					// musicPlayerA.getControl("VolumeControl");
					// volumeControl.setLevel(100);
				} else {
					inputStreamA.close();
					inputStreamA = null;
					inputStreamB = new ByteArrayInputStream(chunkData);
					if (musicPlayerB == null) {
						// System.out.println("Yeah! musicPlayerB is null");
					}
					try {
						musicPlayerB = Manager.createPlayer(inputStreamB, "audio/x-wav");
						// musicPlayerB = Manager.createPlayer(inputStream,
						// "audio/mpeg");
					} catch (Exception e) {
						e.printStackTrace();
						try {
							musicPlayerB = Manager.createPlayer(inputStreamB, "audio/mp3");
						} catch (Exception e2) {
							e.printStackTrace();
						}
					}
					musicPlayerB.prefetch();
					musicPlayerB.addPlayerListener(this);

					// if (loopMusic) {
					// // use the loop count method for infinite looping
					// playerA.setLoopCount(-1);
					// }

					// volumeControl = (VolumeControl)
					// musicPlayerB.getControl("VolumeControl");
					// volumeControl.setLevel(100);

				}

				currentChunkId = chunkId;
			}

		} catch (Exception e) {
		}
	}

	private void updateBufferSong() {
		if (musicPlayerA == null || musicPlayerB == null) {
			// System.out.println("+++++++++++++++++++++Request next chunk " +
			// currentChunkId);
			BeUSession.requestNextChunkAudio(currentSongId, currentChunkId);
		}
	}

	public void logOff() {
		// System.out.println("Logoff App ++++++++++++++++++++++++++++++++++++++");
		playerPage = null;
		removePage(PageConstant.BUDDY_PAGE_ID, false);
		removePage(PageConstant.YAHOO_BUDDY_PAGE_ID, false);
		buddyPage = null;
		yahooBuddyPage = null;
		progressPage = null;
		chatListPage = null;
		buddyInviteConferencePage = null;
		if (friendListModel != null) {
			friendListModel.removeAll();
			friendListModel = null;
		}
		if (yahooFriendListModel != null) {
			yahooFriendListModel.removeAll();
			yahooFriendListModel = null;
		}
		if (conferenceListPages != null) {
			conferenceListPages.removeAllElements();
			// conferencePages = null;
		}
		if (conferenceListName != null) {
			conferenceListName.removeAll();
			// conferencePages = null;
		}
		if (chatListName != null) {
			chatListName.removeAll();
			// chatListName = null;
		}
		if (chatPagesList != null) {
			chatPagesList.removeAllElements();
			// chatPagesList = null;
		}
		if (userInfo != null) {
			userInfo.removeAllElements();
			// userInfo = null;
		}
		if (blackList != null) {
			blackList.removeAll();
			// userInfo = null;
		}
		if (waitingConfirmConference != null) {
			waitingConfirmConference.removeAllElements();
		}
		username = null;
		yahooUsername = null;
		isLoginSuccess = false;
	}

	public void updateStatusOnline(long[] userIds, byte[] levelData) {
		int n = friendListModel.getSize();
		for (int i = 0; i < userIds.length; i++) {
			long userId = userIds[i];
			byte level = levelData[i];
			for (int j = 0; j < n; j++) {
				Buddy b = (Buddy) friendListModel.getItemAt(j);
				if (b != null && b.getUserId() == userId) {
					b.setStatus(ClientConstant.ONLINE);
					b.setLevel(level);
					break;
				}
			}
		}
	}

	public void onChangeAvatarBeanComing(long userId, int avatarId) {
		// System.out.println("onChangeAvatarBeanComing userId " + userId +
		// " avatarId " + avatarId);
		int n = friendListModel.getSize();
		for (int i = 0; i < n; i++) {
			Buddy b = (Buddy) friendListModel.getItemAt(i);
			if (b != null && b.getUserId() == userId) {
				b.setAvatarId(avatarId);
				if (avatarId > 0) { // check have avatar yet
					byte[] imageData = loadAvatarFromRMS(avatarId);
					if (imageData != null) {
						try {
							// System.out.println("onChangeAvatarBeanComing imageData "
							// + imageData.length);
							Image avatar = Image.createImage(imageData, 0, imageData.length);
							b.getAvatarLabel().setIcon(avatar);
						} catch (Exception e) {
							e.printStackTrace();
						}
					} else {
						// System.out.println("onChangeAvatarBeanComing request avatar");
						BeUSession.requestAvatarImage(avatarId, b.getUserId());
					}
				}
				break;
			}
		}
	}

	public void onImageAvatarResultComing(int avatarId, long userId, byte[] imageData) {
		// System.out.println("onImageAvatarResultComing " + avatarId +
		// " length " + imageData.length);
		saveAvatarToRMS(avatarId, imageData);

		int n = friendListModel.getSize();
		for (int i = 0; i < n; i++) {
			Buddy b = (Buddy) friendListModel.getItemAt(i);
			if (b != null && b.getUserId() == userId) {
				b.setAvatarId(avatarId);
				if (imageData != null) {
					try {
						Image avatar = Image.createImage(imageData, 0, imageData.length);
						b.getAvatarLabel().setIcon(avatar);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				break;
			}
		}
	}

	public void onLazyBuddyInfoComing(long userId, int avatarId) {
		// System.out.println("onLazyBuddyInfoComing " + userId + " avatarId " +
		// avatarId);
		int n = friendListModel.getSize();
		for (int i = 0; i < n; i++) {
			Buddy b = (Buddy) friendListModel.getItemAt(i);
			if (b != null && b.getUserId() == userId) {
				b.setAvatarId(avatarId);
				byte[] imageData = loadAvatarFromRMS(avatarId);
				if (imageData != null) {
					try {
						Image avatar = Image.createImage(imageData, 0, imageData.length);
						b.getAvatarLabel().setIcon(avatar);
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					BeUSession.requestAvatarImage(avatarId, b.getUserId());
				}
				break;
			}
		}
	}

	public void onIpListComing(String[] ips, int[] ports) {
		saveIPs(ips);
		savePorts(ports);
	}

	public void onYahooFriendlistComing(String yahooUsername, DefaultListModel buddies) {
		this.yahooUsername = "Y!M " + yahooUsername;
		yahooFriendListModel = buddies;
		if (yahooBuddyPage == null) {
			yahooBuddyPage = new YahooBuddyPage(PageConstant.YAHOO_BUDDY_PAGE_ID, -1);
			yahooBuddyPage.run(this, false);
		}
		createYahooBuddyPage();
	}

	public void onYahooNofifyChangeStatusComing(String yName, byte status, String statusText) {
		String text = null;
		String ymName = "Y!M " + yName;
		if (status == ClientConstant.ONLINE) {
			text = ymName + Language.USER_ONLINE[ClientConstant.LANGUAGE];
		} else {
			text = ymName + Language.USER_OFF_INVI[ClientConstant.LANGUAGE];
		}
		// System.out.println("onChangeStatusComing: " + text);
		showSystemMessage(text, null, status);
		// first handshake
		Page cur = getCurrentPage();
		if (cur instanceof ChatPage) {
			ChatPage p = (ChatPage) currentPage;
			if (p.getOrginalTitle().equals(ymName)) {
				p.addItems(ymName, text);
				return;
			}
		}
		ChatPage page = addChatPage(ymName, false, false);
		if (page != null) {
			page.addItems(ymName, text);
		}
		updateBuddyInfoYahoo(yName, status, statusText);
	}

	public void onYahooChatFromComing(String yName, String msgChat) {
		String ymName = "Y!M " + yName;
		Page cur = getCurrentPage();
		if (cur instanceof ChatPage) {
			ChatPage p = (ChatPage) currentPage;
			if (p.getOrginalTitle().equals(ymName)) {
				p.addItems(ymName, msgChat);
				return;
			}
		}
		ChatPage page = addChatPage(ymName, false, true);
		if (page != null) {
			page.addItems(ymName, msgChat);
			addOrUpdateChatListModel(ymName);
			showSystemMessage(ymName + " đang chat", null, (byte) 1);
		}
	}

	public void onYahooBuzztFromComing(String yName) {
		String ymName = "Y!M " + yName;
		Page cur = getCurrentPage();
		if (cur instanceof ChatPage) {
			ChatPage p = (ChatPage) currentPage;
			if (p.getOrginalTitle().equals(ymName)) {
				p.addItems(ymName, "Hù!");
				startVibrate();
				playSound();
				return;
			}
		}
		ChatPage page = addChatPage(ymName, false, true);
		if (page != null) {
			page.addItems(ymName, "Hù!");
			addOrUpdateChatListModel(ymName);
			showSystemMessage(ymName + " hù!", null, (byte) 1);
			startVibrate();
			playSound();
		}
	}

}
